package vn.edu.thptduongbachmai.services;

import com.vng.zing.configer.ZConfig;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import org.apache.log4j.Logger;

/**
 *
 * @author tiennv4
 */
public class MySQLService extends DBService {

    private static Logger _Logger = Logger.getLogger(MySQLService.class);
    private static DBService _instance;
    public  String getDbName ()
    {
        return _dbname;
    }
    private MySQLService(String name) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            _host = ZConfig.Instance.getString(MySQLService.class, name, "host", "127.0.0.1");
            _port = ZConfig.Instance.getInt(MySQLService.class, name, "port", 3306);
            _dbname = ZConfig.Instance.getString(MySQLService.class, name, "dbname", "bachmaischool");
            _username = ZConfig.Instance.getString(MySQLService.class, name, "username", "root");
            _password = ZConfig.Instance.getString(MySQLService.class, name, "password", "123");
            _poolSize = ZConfig.Instance.getInt(MySQLService.class, name, "pool_size", 10);
            _url = "jdbc:mysql://" + _host + ":" + _port + "/" + _dbname
                    + "?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&interactiveClient=true&"
                    + "&user=" + _username + "&password=" + _password;



            BlockingQueue<Connection> cnnPool = new ArrayBlockingQueue<Connection>(_poolSize);
            while (cnnPool.size() < _poolSize) {
                cnnPool.add(DriverManager.getConnection(_url));
            }
            _pool = cnnPool;

        } catch (Exception ex) {
            _Logger.warn(ex);
        }
    }

    public static DBService getInstance(String name) {
        synchronized (_mutex) {
            if (_instance == null) {
                _instance = new MySQLService(name);
            }
        }
        return _instance;
    }

    @Override
    public Connection getDbConnection() {
        Connection conn = null;
        do {
            try {
                conn = _pool.take();
                if (conn == null || !conn.isValid(0)) {
                    conn = DriverManager.getConnection(_url);
                }
            } catch (Exception ex) {
                _Logger.warn(ex +" "+_url);
            }
        } while (conn == null);
        return conn;
    }

    @Override
    public void releaseDbConnection(Connection conn) {

        _pool.add(conn);
    }
}
